package be.vdabantwerpen.gow.dao;

import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import be.vdabantwerpen.gow.entities.Post;
import be.vdabantwerpen.gow.entities.GOWUser;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.repackaged.org.joda.time.DateTime;
import java.util.ArrayList;

public class PostDAOImpl implements PostDAO {
    private final DatastoreService datastore = 
            DatastoreServiceFactory.getDatastoreService();
    private final UserDAO userdao = new UserDAOImpl();

	@Override
	public void create(Post post) {
            Entity e = toEntity(post);
            datastore.put(e);
	}

	@Override
	public Post read(int postId) {
            Entity e = new Entity("Post", postId);
            try {
                return toPost(datastore.get(e.getKey()));
            }
            catch(EntityNotFoundException enfe){
                return null;
            }
	}

	@Override
	public void update(Post post) {
            Entity e = toEntity(post);
            datastore.put(e);
	}

	@Override
	public void delete(Post post) {
            Entity e = toEntity(post);
            datastore.delete(e.getKey());
	}

	@Override
	public List<Post> findAll() {
            List<Post> posts = new ArrayList();
            Query q = new Query("Post");
            PreparedQuery pq = datastore.prepare(q);
            for(Entity e : pq.asIterable()){
                posts.add(toPost(e));
            }
            return posts;
	}
        
        private Post toPost(Entity entity){
            DateTime date = DateTime.parse(entity.getProperty("date").toString());
            int userId = 0;
            GOWUser user = null;
            try {
                userId = Integer.valueOf(entity.getProperty("user").toString());
                if(userId > 0){
                    user = userdao.read(userId);
                }
            }
            catch(NumberFormatException nfe){
                
            }
            String content = entity.getProperty("content").toString();
            Post post = new Post(user, date, content);
            return post;
        }
        
        private Entity toEntity(Post post){
            Entity entity = new Entity("Post", post.hashCode());
            entity.setProperty("content", post.getContent());
            entity.setProperty("user", post.getUser().getUserId());
            entity.setProperty("date", post.getDate().toString());
            return entity;
        }

}
